﻿
//needs to be cleared anytime the candidate dlg is opened, set
//when a heard about is chosen
var CandidateDlg_HeardAboutID = -1;

var CANDIDATE_PAGE_URL = "";

// Used to make sure the user wants to add that candidate (closely related to another candidate)
var AddCandidateCheck = false;

//this function runs on document.ready()
$(function () {
    //create an add candidate popup dlg
    $("#AddCandidatePopup").dialog({
        modal: true,
        resizable: false,
        width: DEFAULT_DLG_WIDTH,
        height: DEFAULT_DLG_HEIGHT,
        position: ['center', 'center'],
        autoOpen: false,
        buttons:
        [
            {
                text: "Add Application",
                click: function () { OnAddCandidateClicked(true); }
            },
            {
                text: "Finish",
                click: function () { OnAddCandidateClicked(false); }
            },
            {
                text: "Cancel",
                click: function () { $(this).dialog("close"); }
            }
        ],
        title: "New Candidate",
        open: OnAddCandidateDlgOpen
    });

    // Name box is now a search box
    // setup the search autocomplete
    $("#CandPopup_Name").autocomplete({
        source: CandidateSearchSource,
        select: function (event, ui) {
            //candidate selected, go to candidate view

            window.location = CANDIDATE_PAGE_URL + '?candID=' + ui.item.itemID;
            return false;
        },
        delay: 10 //todo how does this feel with lots of data?
    });

    //catch the 'enter' keydown for the 'search' control
    //route to candidate list view
    $("CandPopup_Name").keydown(function (e) {
        if (e.keyCode == 13) {
            window.location = CANDIDATE_PAGE_URL + '?candID=' + ui.item.itemID; //SEARCH_PAGE_URL + '?q=' + $(this).val();
            //keep weird behavior from occuring
            e.preventDefault();
        }
    });

    //make the heard about box a jquery ui combobox
    $("#CandPopup_HeardAbout").combobox({
        valueselect: function (event, ui) { CandidateDlg_HeardAboutID = ui.item.itemID; },
        source: []
    });
    //make the heard about a true combo box, not editable
    $("#CandPopup_Combobox").find("input").attr('readonly', 'readonly');
});

function CandidateSearchSource(request, response) {
    //retrieve candidates based on search value in input
    PageMethods.GetAllCandidates_Json(request.term,
    function (json) {
        //send the received data to the control
        response(eval(json));

    },
    function () {
        //error occured, set empty data
        response([]);
    }
    );
}

function OnAddCandidateDlgOpen() {

    //reset this, in case dialog was opened previously
    CandidateDlg_HeardAboutID = -1;

    //reset any errors or messages
    $("#AddCandidatePopup").find("input").val('');
    $("#AddCandidatePopup").find("textarea").val('');
    $("#AddCandidatePopup").find(".ui-state-error").removeClass("ui-state-error");
    $("#CandPopup_Message").addClass("ui-helper-hidden");
    $("#CandPopup_Error").addClass("ui-helper-hidden");

    // Get all candidates from the database
    // For the search bar

    //get heard abouts from the database
    PageMethods.GetAllHeardAbouts_Json(
        function (json) {
            //send this data to the combobox
            $("#CandPopup_HeardAbout").combobox("option", "source", eval(json));
        },
        function () {
            //TODO: show error message
            $("#CandPopup_Combobox").addClass("ui-state-error");

            //set empty data
            $("#CandPopup_HeardAbout").combobox("option", "source", []);
        }
    );
}

function OnAddCandidateClicked(bGoToApplication) {
    CheckCandidateDlg_IsAddingApp = bGoToApplication;

    //clear out any messages
    $("#CandPopup_Message").addClass("ui-helper-hidden");
    $("#CandPopup_Error").addClass("ui-helper-hidden");

    //get all the data
    var name = $("#CandPopup_Name");
    CheckCandidateDlg_Name = name.val();
    var email = $("#CandPopup_Email");
    CheckCandidateDlg_Email = email.val();
    var phone = $("#CandPopup_Phone");
    CheckCandidateDlg_Phone = phone.val();
    var heard = $("#CandPopup_Combobox").find("input").first();
    var heardContainer = $("#CandPopup_HeardAbout");
    CheckCandidateDlg_HeardAboutID = CandidateDlg_HeardAboutID;
    var notes = $("#CandPopup_Notes");
    CheckCandidateDlg_HeardAboutNotes = notes.val();

    //validate the data
    var bValid = true;

    //name can't be empty
    if (name.val().length == 0) {
        name.addClass("ui-state-error");
        bValid = false;
    }
    else {
        name.removeClass("ui-state-error");
    }

    //heard about can't be empty
    if (CandidateDlg_HeardAboutID == -1) {
        heard.addClass("ui-state-error");
        bValid = false;
    }
    else {
        heard.removeClass("ui-state-error");
    }

    //TODO: warn if they are adding a new heard about to database

    if (bValid) {
        //valid, so add the candidate and close the dialog

        // Check to see if user wants to create a candidate with the same 
        // name as another candidate
        PageMethods.CheckCandidate(name.val(),
        //PageMethods.CheckCandidates_Json(name.val(),
            function (check) {
                if (check) {
                    CheckCandidateDlg_Name = name.val();
                    ShowPopup("#CheckCandidatePopup");
                }
                else {
                    //call page methods to add candidate
                    PageMethods.CreateCandidate(name.val(), email.val(), phone.val(), CandidateDlg_HeardAboutID, notes.val(),
                        function (newID) {
                            //TODO Show success msgg???

                            //close the dlg
                            $("#AddCandidatePopup").dialog("close");

                            //if user hits 'new application' go directly to that dialog
                            //with new candidate already selected
                            if (bGoToApplication) {
                                ApplicationDlg_CurrentCandidateID = newID;
                                ShowPopup("#AddApplicationPopup");
                            }
                        },
                        function () {
                            //error, show message and don't close dlg
                            $("#CandPopup_Error").removeClass("ui-helper-hidden");
                        }
                    ); // end: PageMethods.CreateCandidate
                } // end: else
            },
            function () { }
        ); // end: PageMethods.CheckCandidate
    } // end: if (bValid)
}